<!-- 库存调拨 -->
<template>
    <el-form :model="dictform" ref="dictref" :inline="true" style="text-align: left;">
        <el-form-item label="调拨单号:" prop="al_code">
            <el-input placeholder="请输入编号" v-model="dictform.al_code" style="width:180px"></el-input>
        </el-form-item>
        <!-- 单据状态 -->
        <el-form-item label="单据状态" prop="al_status">
        <el-select placeholder="请选择" v-model="dictform.al_status" style="width:200px">
            <!-- 修改这里：使用alstatusdata字典数据 -->
            <el-option 
            v-for="item in alstatusdata"
            :key="item.dict_sort"
            :value="item.dict_sort"
            :label="item.dict_label">
            </el-option>
        </el-select>
        </el-form-item>

        <!-- 出入库状态 -->
        <el-form-item label="出入库状态" prop="instockoutstock_status">
            <el-select v-model="dictform.instockoutstock_status" placeholder="请选择" style="width:200px">
                <!-- 入库状态 -->
                <el-option-group v-for="group in instockoutstockOptions" :key="group.label" :label="group.label">
                    <el-option
                        v-for="item in group.options"
                        :key="item.dict_sort"
                        :label="item.dict_label"
                        :value="item.dict_sort"
                    />
                </el-option-group>
            </el-select>
        </el-form-item>
        <el-form-item label="调拨申请日">
            <el-date-picker
                v-model="dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width:280px"
                @change="handleDateChange"
            />
        </el-form-item>
        <el-form-item>
            <el-button @click="Reset">重置</el-button>
            <el-button type="success" @click="Search">查询</el-button>
            <el-button @click="drawer = true">高级查询</el-button>
        </el-form-item>
    </el-form>
    <div style="text-align: left;">
        <el-button type="success" @click="jump()">添加</el-button>
        <el-button @click="DeleteAll">删除</el-button>
        <el-button @click="GetEnable">审核</el-button>
        <el-button @click="exportData">导出</el-button>
    </div>
    <!--表格-->
    <el-table :data="displayData" style="margin-top: 10px;" @selection-change="SelectChange" ref="tableRef">
            <!-- 左侧固定列 -->
            <el-table-column fixed type="selection"></el-table-column>
            <el-table-column fixed type="index" label="序号" width="70"></el-table-column>
            <el-table-column fixed label="调拨单号" width="200">
                <template #default="scope">
                    <span class="clickable-cell" :style="{ color: scope.row.al_status != 1 ? 'green' : '', cursor: scope.row.al_status != 1 ? 'pointer': '' }" @click="scope.row.al_status != 1 ? Jumptodetail(scope.row.al_id,scope.row.al_code) : null">
                        {{ scope.row.al_code }}
                    </span>
                </template>
            </el-table-column>
            <el-table-column fixed prop="alstatus_name" label="单据状态" width="150px"></el-table-column>
            <el-table-column fixed prop="al_date" label="调拨申请日期" width="200"></el-table-column>

            <!-- 中间可滚动列，为每列设置明确宽度 -->
            <el-table-column prop="al_type" label="调拨类型" width="120"></el-table-column>
            <el-table-column prop="out_wh_name" label="调出仓库" width="100"></el-table-column>
            <el-table-column prop="in_wh_name" label="调入仓库" width="130"></el-table-column>
            <el-table-column prop="outstock_name" label="出库状态" width="150"></el-table-column>
            <el-table-column prop="instock_name" label="入库状态" width="120"></el-table-column>
            <el-table-column prop="al_num" label="调拨数量" width="120"></el-table-column>
            <el-table-column prop="al_total" label="调拨金额" width="120">
                <template #default="scope">
                    {{ scope.row.al_total ? Number(scope.row.al_total).toFixed(2) : '0.00' }}
                </template>
            </el-table-column>
            <el-table-column prop="al_user" label="经办人" width="120"></el-table-column>
            <el-table-column prop="proc_list" show-overflow-tooltip = "true" label="调拨货品" width="150"></el-table-column>
            <el-table-column prop="create_name" label="制单人" width="120"></el-table-column>
            <el-table-column prop="create_time" label="制单时间" width="200"></el-table-column>
            <el-table-column prop="approver_name" label="审核人" width="200"></el-table-column>
            <el-table-column prop="approver_time" label="审核时间" width="200"></el-table-column>
            
            <!-- 右侧固定列 -->
            <el-table-column fixed="right" label="操作" width="155px">
                <template #default="scope">
                    <el-button
                        v-if="scope.row.alstatus_name !== '通过' && scope.row.alstatus_name !== '已完成' && scope.row.alstatus_name !== '驳回'"
                        type="success"
                        text="编辑"
                        @click="jump(scope.row.al_id)"
                    >
                        编辑
                    </el-button>
                    <el-button
                        v-if="scope.row.alstatus_name !== '通过' && scope.row.alstatus_name !== '已完成' && scope.row.alstatus_name !== '驳回'"
                        type="danger"
                        text="删除"
                        @click="deletiondata(scope.row.al_id)"
                    >
                        删除
                    </el-button>
                    <el-button
                        v-if="scope.row.alstatus_name == '驳回'"
                        type="success"
                        text="撤销"
                        @click="quash(scope.row.al_id)"
                    >
                    撤销
                    </el-button>
                </template>
            </el-table-column>
    </el-table>

    <!-- 移植的页码组件 -->
    <el-pagination :page-size="10" :pager-count="11" layout="prev, pager, next, jumper" :total="rows" @current-change="handlePageChange" style="float:right;margin-top:20px"></el-pagination>

    <!-- 高级查询 -->
    <el-drawer v-model="drawer">
        <template #header>
            <h4 style="text-align: left;">高级查询</h4>
        </template>
        <template #default>
            <el-form :model="updateform" ref="updateformref" :rules="rules" label-width="auto" style="text-align: left;">
                <el-row :gutter="20">
                    <!-- 左侧列 -->
                    <el-col :span="12">
                        <el-form-item label="调拨单号" prop="al_code">
                            <el-input placeholder="请输入" v-model="supplierformsenior.al_code"></el-input>
                        </el-form-item>
                    </el-col>
                    
                    <!-- 右侧列 -->
                    <el-col :span="12">
                        <el-form-item label="单据状态" prop="al_status">
                            <el-select placeholder="请选择" v-model="supplierformsenior.al_status" style="width:200px">
                                <el-option 
                                v-for="item in alstatusdata"
                                :key="item.dict_sort"
                                :value="item.dict_sort"
                                :label="item.dict_label">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <!-- 在高级查询的 el-drawer 中添加 -->
                    <el-col :span="24">
                        <el-form-item label="出入库状态" prop="stockStatus">
                            <!-- 入库状态 -->
                            <div style="margin-bottom: 10px;">
                            <span>入库状态</span>
                            <el-checkbox-group v-model="supplierformsenior.instock_status" style="display: inline-block; margin-left: 10px;">
                                <el-checkbox 
                                v-for="item in instockstatusdata" 
                                :key="item.dict_sort" 
                                :label="item.dict_sort"
                                style="margin-right: 20px;"
                                >
                                {{ item.dict_label }}
                                </el-checkbox>
                            </el-checkbox-group>
                            </div>

                            <!-- 出库状态 -->
                            <div>
                            <span>出库状态</span>
                            <el-checkbox-group v-model="supplierformsenior.outstock_status" style="display: inline-block; margin-left: 10px;">
                                <el-checkbox 
                                v-for="item in outstockstatusdata" 
                                :key="item.dict_sort" 
                                :label="item.dict_sort"
                                style="margin-right: 20px;"
                                >
                                {{ item.dict_label }}
                                </el-checkbox>
                            </el-checkbox-group>
                            </div>
                        </el-form-item>
                    </el-col>
                    
                    <!-- 左侧列 -->
                    <el-col :span="12">
                        <el-form-item label="调拨申请日">
                            <el-date-picker
                                v-model="requesttransferdateRange"
                                type="daterange"
                                range-separator="至"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期"
                                format="YYYY-MM-DD"
                                value-format="YYYY-MM-DD"
                                @change="requesttransferhandleDateChange"
                            />
                        </el-form-item>
                        <el-form-item label="调出仓库" prop="out_wh_id">
                            <el-select placeholder="请选择" v-model="supplierformsenior.out_wh_id" style="width:200px">
                                <el-option 
                                v-for="item in warehousedata"
                                :key="item.wh_id"
                                :value="item.wh_id"
                                :label="item.wh_name">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="经办人" prop="al_user">
                            <el-select placeholder="请选择" v-model="supplierformsenior.al_user" style="width:200px">
                                <el-option 
                                v-for="item in userdata"
                                :key="item.user_id"
                                :value="item.user_name"
                                :label="item.user_name">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="制单时间">
                            <el-date-picker
                                v-model="createdateRange"
                                type="daterange"
                                range-separator="至"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期"
                                format="YYYY-MM-DD"
                                value-format="YYYY-MM-DD"
                                @change="createhandleDateChange"
                            />
                        </el-form-item>
                        <el-form-item label="审核人" prop="approver_name">
                            <el-select placeholder="请选择" v-model="supplierformsenior.approver_name" style="width:200px">
                                <el-option 
                                v-for="item in userdata"
                                :key="item.user_id"
                                :value="item.user_name"
                                :label="item.user_name">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    
                    <!-- 右侧列 -->
                    <el-col :span="12">
                        <el-form-item label="调拨类型" prop="al_type">
                            <el-select placeholder="请选择" v-model="supplierformsenior.al_type" style="width:200px">
                                <el-option 
                                v-for="item in Allocationtype"
                                :key="item.bus_id"
                                :value="item.bus_name"
                                :label="item.bus_name">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="调入仓库" prop="in_wh_id">
                            <el-select placeholder="请选择" v-model="supplierformsenior.in_wh_id" style="width:200px">
                                <el-option 
                                v-for="item in warehousedata"
                                :key="item.wh_id"
                                :value="item.wh_id"
                                :label="item.wh_name">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="制单人" prop="create_name">
                            <el-select placeholder="请选择" v-model="supplierformsenior.create_name" style="width:200px">
                                <el-option 
                                v-for="item in userdata"
                                :key="item.user_id"
                                :value="item.user_name"
                                :label="item.user_name">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="审核时间">
                            <el-date-picker
                                v-model="auditdateRange"
                                type="daterange"
                                range-separator="至"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期"
                                format="YYYY-MM-DD"
                                value-format="YYYY-MM-DD"
                                @change="audithandleDateChange"
                            />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </template>
        <template #footer>
            <div style="flex: auto">
                <el-button @click="resetSeniorForm">重置</el-button>
                <el-button @click="drawer = false">关闭</el-button>
                <el-button type="primary" @click="GetSeniorFenYe">查询</el-button>
            </div>
        </template>
    </el-drawer>
    <!-- 在模板中添加审核对话框 -->
<!--审核模态框-->
    <el-dialog v-model="showAuditDialog" title="审核" width="400" style="text-align: left;" align-center>
        <div>
            <div style="margin-bottom: 15px;">
                <div>审核结果</div>
                <div style="margin-top: 10px;">
                    <el-radio v-model="auditForm.status" label="通过" style="margin-right: 20px;" value="9">通过</el-radio>
                    <el-radio v-model="auditForm.status" label="驳回" value="3">驳回</el-radio>
                </div>
            </div>
            <div>
                <div>审核意见</div>
                <el-input 
                    v-model="auditComment" 
                    type="textarea" 
                    rows="5" 
                    placeholder="请输入"
                    style="margin-top: 10px;"
                ></el-input>
            </div>
        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="showAuditDialog = false">取消</el-button>
                <el-button type="primary" @click="submitAudit()">确定</el-button>
            </div>
        </template>
    </el-dialog>
</template>
<script>
import { ref, reactive, onMounted, watch, nextTick, computed } from 'vue';
import http from '../auth/index';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router';
import * as XLSX from 'xlsx';
import qs from 'qs';

export default {
    setup() {
        const router = useRouter();

        const rules = reactive({
            Role_name: [
                { required: true, message: '角色名称不能为空', trigger: 'blur' }
            ],
            Role_sort: [
                { required: true, message: '排序不能为空', trigger: 'change' }
            ]
        });
        //#region 查询相关

        // 日期范围
        const dateRange = ref([]);
        // 开始和结束时间
        const startTime = ref('');
        const endTime = ref('');

        // 处理日期变化
        function handleDateChange(dates) {
            if (dates && dates.length === 2) {
                startTime.value = dates[0] + ' 00:00:00';
                endTime.value = dates[1] + ' 23:59:59';
            } else {
                startTime.value = '';
                endTime.value = '';
            }
        }
        
        // 翻页相关变量 - 从第一个文件移植
        const rows = ref(0);          // 总数据量
        const currentPage = ref(1);   // 当前页码
        
        // 表单引用和状态
        const dictref = ref(null);
        const dictform = reactive({
            al_code:"",
            al_status:"",
            instockoutstock_status:null
        });
        
        // 表格数据
        const dictdata = ref([]);
        const alstatusdata = ref([]);
        const instockstatusdata = ref([]);
        const outstockstatusdata = ref([]);
        const warehousedata = ref([]);
        const userdata = ref([]);
        const Allocationtype = ref([]);

        // 翻页方法 - 从第一个文件移植
        function handlePageChange(page) {
            currentPage.value = page;
            All();
        }

        function Reset() {
            dictref.value?.resetFields();
            
            // 添加手动重置确保生效
            dateRange.value = [];
            startTime.value = '';
            endTime.value = '';
        }

        // 查询数据
        function Search() {
            currentPage.value = 1; // 重置到第一页
            All();
        }

        // 日期转换格式
        function formatDateTime(dateStr) {
            if (!dateStr) return '';
            const date = new Date(dateStr);
            if (isNaN(date.getTime())) return '';
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');
            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        }

        // 获取数据 - 修改为使用分页参数
        function All() {
            http.get("/Allot_h/GetFenYe", {
                params: {
                    CurrentPage: currentPage.value,
                    al_code: dictform.al_code,
                    al_status: dictform.al_status,
                    instockoutstock_status: dictform.instockoutstock_status,
                    startTime: startTime.value, // 开始时间
                    endTime: endTime.value     // 结束时间
                }
            }).then(res => {
                // 确保正确获取总记录数和列表数据
                rows.value = res.data.rows; 
                
                // 格式化日期时间字段
                dictdata.value = res.data.list.map(item => ({
                    ...item,
                    al_date: formatDateTime(item.al_date),
                    create_time: formatDateTime(item.create_time),
                    approver_time: item.approver_time ? formatDateTime(item.approver_time) : ''
                }));
                dictdata.value.sort((a, b) => new Date(b.create_time) - new Date(a.create_time));
                
                // 调试信息
                console.log("总记录数:", rows.value);
                console.log("当前页数据:", dictdata.value);
            }).catch(err => {
                console.error("获取数据失败:", err);
                ElMessage.error("获取数据失败，请重试");
            });
        }
        
        //查询入库状态
        function instockstatus() {
            http.get("/Supplier/GetDictData", {
                params: {
                    dict_id: 15
                }
            }).then(res => {
                console.log("入库:", res.data); // 调试用
                instockstatusdata.value = res.data; // 将查询结果赋值给 Departmentdata
            }).catch(err => {
                console.log(err);
                ElMessage.error('数据加载失败');
            });
        }
        
        //查询出库状态
        function outstockstatus() {
            http.get("/Supplier/GetDictData", {
                params: {
                    dict_id: 14
                }
            }).then(res => {
                console.log("出库:", res.data); // 调试用
                outstockstatusdata.value = res.data; // 将查询结果赋值给 Departmentdata
            }).catch(err => {
                console.log(err);
                ElMessage.error('数据加载失败');
            });
        }
        
        //查询单据状态
        function alstatus() {
            http.get("/Supplier/GetDictData", {
                params: {
                    dict_id: 6
                }
            }).then(res => {
                console.log("单据:", res.data); // 调试用
                alstatusdata.value = res.data; // 将查询结果赋值给 Departmentdata
            }).catch(err => {
                console.log(err);
                ElMessage.error('数据加载失败');
            });
        }
        
        //查询调拨类型
        function GetAllocationtype() {
            http.get("/BusinessType/GetBusinessTypes", {
                params: {
                    field: '调拨'
                }
            }).then(res => {
                console.log("调拨:", res.data); // 调试用
                Allocationtype.value = res.data; // 将查询结果赋值给 Departmentdata
            }).catch(err => {
                console.log(err);
                ElMessage.error('数据加载失败');
            });
        }
        
        // 在 setup() 中添加
        const displayData = computed(() => {
            if (!alstatusdata.value.length || !outstockstatusdata.value.length || !instockstatusdata.value.length) {
                return []; // 基础数据未加载时返回空数组
            }
            
            return dictdata.value.map(user => {
                // 查找入库状态名称
                const instock = instockstatusdata.value.find(
                    ins => ins.dict_value == user.instock_status
                );
                
                // 查找出库状态名称
                const outstock = outstockstatusdata.value.find(
                    out => out.dict_value == user.outstock_status
                );
                
                // 查找单据状态名称
                const alstatus = alstatusdata.value.find(
                    als => als.dict_value == user.al_status
                );
                
                return {
                    ...user,
                    instock_name: instock?.dict_label || '未知入库状态',
                    outstock_name: outstock?.dict_label || '未知出库状态',
                    alstatus_name: alstatus?.dict_label || '未知单据状态',
                };
            });
        });

        // 新增 computed 属性，合并入库和出库状态
        const instockoutstockOptions = computed(() => {
            return [
                {
                    label: '入库状态',
                    options: instockstatusdata.value
                },
                {
                    label: '出库状态',
                    options: outstockstatusdata.value
                }
            ];
        });
        
        //查询仓库名
        function GetWarehouses() {
            http.get("/Warehouse/GetWarehouses").then(res => {
                console.log("仓库:", res.data); // 调试用
                warehousedata.value = res.data; // 将查询结果赋值给 Departmentdata
            }).catch(err => {
                console.log(err);
                ElMessage.error('数据加载失败');
            });
        }
        
        //查询用户名
        function GetUser() {
            http.get("/User/GetAllUser").then(res => {
                console.log("用户:", res.data); // 调试用
                userdata.value = res.data; // 将查询结果赋值给 Departmentdata
            }).catch(err => {
                console.log(err);
                ElMessage.error('数据加载失败');
            });
        }

        const drawer = ref(false);

        //高级查询表单
        const supplierformsenior = reactive({
            al_code:"",
            al_status:null,
            instock_status:[],
            outstock_status:[],
            al_type:"",
            create_name:"",
            out_wh_id:null,
            in_wh_id:null,
            al_user:"",
            approver_name:""
        })

        // 日期范围
        const requesttransferdateRange = ref([]);
        // 开始和结束时间
        const requesttransferstartTime = ref('');
        const requesttransferendTime = ref('');

        // 处理日期变化
        function requesttransferhandleDateChange(dates) {
            if (dates && dates.length === 2) {
                requesttransferstartTime.value = dates[0] + ' 00:00:00';
                requesttransferendTime.value = dates[1] + ' 23:59:59';
            } else {
                requesttransferstartTime.value = '';
                requesttransferendTime.value = '';
            }
        }
        
        // 日期范围
        const createdateRange = ref([]);
        // 开始和结束时间
        const createstartTime = ref('');
        const createendTime = ref('');

        // 处理日期变化
        function createhandleDateChange(dates) {
            if (dates && dates.length === 2) {
                createstartTime.value = dates[0] + ' 00:00:00';
                createendTime.value = dates[1] + ' 23:59:59';
            } else {
                createstartTime.value = '';
                createendTime.value = '';
            }
        }
        
        // 日期范围
        const auditdateRange = ref([]);
        // 开始和结束时间
        const auditstartTime = ref('');
        const auditendTime = ref('');

        // 处理日期变化
        function audithandleDateChange(dates) {
            if (dates && dates.length === 2) {
                auditstartTime.value = dates[0] + ' 00:00:00';
                auditendTime.value = dates[1] + ' 23:59:59';
            } else {
                auditstartTime.value = '';
                auditendTime.value = '';
            }
        }

        // 高级查询
        function GetSeniorFenYe() {
            // 2. 准备参数对象
            const params = {
                CurrentPage: currentPage.value,
                al_code: supplierformsenior.al_code,
                al_status: supplierformsenior.al_status,
                instock_status: supplierformsenior.instock_status, // 数组
                outstock_status: supplierformsenior.outstock_status, // 数组
                al_type: supplierformsenior.al_type,
                create_name: supplierformsenior.create_name, // 添加了 create_name
                out_wh_id: supplierformsenior.out_wh_id,
                in_wh_id: supplierformsenior.in_wh_id,
                al_user: supplierformsenior.al_user,
                approver_name: supplierformsenior.approver_name,
                requesttransferstartTime: requesttransferstartTime.value,
                requesttransferendTime: requesttransferendTime.value,
                createstartTime: createstartTime.value, // 确保这些变量名正确
                createendTime: createendTime.value,
                auditstartTime: auditstartTime.value,
                auditendTime: auditendTime.value
            };

            // 3. 使用 qs 序列化参数，并指定数组格式
            const serializedParams = qs.stringify(params, { arrayFormat: 'indices' }); // 推荐使用 'indices' 或 'brackets'

            // 4. 发送 GET 请求，将序列化后的字符串作为 params 传递
            // 注意：这里使用 paramsSerializer 来指定如何序列化参数
            http.get("/Allot_h/GetSeniorFenYe", {
                params: params, // 传递原始对象
                paramsSerializer: function (params) {
                    // 使用 qs 来序列化，确保数组被正确处理
                    return qs.stringify(params, { arrayFormat: 'indices' }); // 与上面保持一致
                }
            }).then(res => {
                rows.value = res.data.rows;
                // 格式化日期时间字段
                dictdata.value = res.data.list.map(item => ({
                    ...item,
                    al_date: formatDateTime(item.al_date),
                    create_time: formatDateTime(item.create_time),
                    approver_time: item.approver_time ? formatDateTime(item.approver_time) : ''
                }));
                drawer.value = false;
            }).catch(err => {
                console.error("高级查询失败:", err);
                ElMessage.error("查询失败，请重试");
            });
        }

        function resetSeniorForm() {
            // 重置表单字段
            supplierformsenior.al_code = "";
            supplierformsenior.al_status = null;
            supplierformsenior.instock_status = [];
            supplierformsenior.outstock_status = [];
            supplierformsenior.al_type = "";
            supplierformsenior.out_wh_id = null;
            supplierformsenior.in_wh_id = null;
            supplierformsenior.al_user = "";
            supplierformsenior.create_name = "";
            supplierformsenior.approver_name = "";

            // 重置日期范围
            requesttransferdateRange.value = [];
            createdateRange.value = [];
            auditdateRange.value = [];

            // 可选：重置关联的时间变量（如果存在）
            requesttransferstartTime.value = '';
            requesttransferendTime.value = '';
            createstartTime.value = '';
            createendTime.value = '';
            auditstartTime.value = '';
            auditendTime.value = '';
        }
        //#endregion

        //#region 删除、审核、导出
        const selectdata=ref([]);//选中数据
        //获取选中数据
        function SelectChange(val){
            selectdata.value=val;
        }
        const tableRef = ref(null); // 添加表格引用
        function deletiondata(id) {
            ElMessageBox.confirm('确定要删除该调拨单吗？', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                try {
                // 调用后端逻辑删除接口（PUT 方法）
                const res = await http.put('/Allot_h/GetDelete?id='+id);

                if (res.status === 200) {
                    ElMessage.success('删除成功');
                    All();
                }
                } catch (err) {
                    ElMessage.error('删除失败');
                    console.error(err);
                }
            }).catch(() => {
                // 用户取消操作
            });
        }

        // 批量删除
        function DeleteAll() {
            if (selectdata.value.length === 0) {
                ElMessage.warning('请选择要删除的数据');
                return;
            }
            
            ElMessageBox.confirm('确定要删除选中的调拨单吗？', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                const deletePromises = selectdata.value.map(item => {
                    return http.put(`/Allot_h/GetDelete?id=${item.al_id}`);
                });
                
                Promise.all(deletePromises)
                    .then(results => {
                        const successCount = results.filter(res => res.data > 0).length;
                        if (successCount === selectdata.value.length) {
                            ElMessage.success(`成功删除 ${successCount} 条数据`);
                        } else {
                            ElMessage.warning(`成功删除 ${successCount} 条，失败 ${selectdata.value.length - successCount} 条`);
                        }
                        All(); // 刷新数据
                        tableRef.value.clearSelection(); // 清空选中状态
                    })
                    .catch(err => {
                        console.error(err);
                        ElMessage.error('删除失败');
                    });
            }).catch(() => {
                ElMessage.warning('已取消删除');
                return;
            });
        }

        function exportData() {
            if (selectdata.value.length === 0) {
                ElMessage.warning('请选择要导出的数据');
                return;
            }
    
            // 创建工作簿
            const wb = XLSX.utils.book_new();
            const excelData = selectdata.value.map((row) => ({
                "序号": row.al_id,
                "调拨单号": row.al_code,
                "单据状态": row.alstatus_name, // 使用 displayData 中的计算字段
                "调拨申请日期": row.al_date,
                "调拨类型": row.al_type,
                "调出仓库": row.out_wh_name,
                "调入仓库": row.in_wh_name,
                "出库状态": row.outstock_name,
                "入库状态": row.instock_name,
                "调拨数量": row.al_num,
                "调拨金额": row.al_total,
                "经办人": row.al_user,
                "调拨货品": row.proc_list,
                "制单人": row.create_name,
                "制单时间": row.create_time,
                "审核人": row.approver_name,
                "审核时间": row.approver_time
            }));
            // 创建工作表
            const ws = XLSX.utils.json_to_sheet (excelData);
            // 添加到工作簿
            XLSX.utils.book_append_sheet(wb, ws, "调拨数据");
            // 导出并下载
            XLSX.writeFile(wb, `调拨数据${new Date().toLocaleDateString()}.xlsx`);
        }

        // 在setup()中添加相关响应式数据和方法
        const showAuditDialog = ref(false);
        const auditForm = reactive({
        status: 3,
        selectedIds: []
        });

        // 审核方法
        function GetEnable() {
            if (selectdata.value.length === 0) {
                ElMessage.warning('请选择要审核的数据');
                return;
            }

            // 定义不能被审核的状态值 (根据您的描述: 3=驳回, 6=通过, 9=已完成)
            const forbiddenStatuses = [1,3, 6, 9];
            const forbiddenStatusLabelMap = { 1: '草稿', 3: '驳回', 6: '通过', 9: '已完成' }; // 用于显示提示信息

            // 分离出可以审核和不可以审核的项
            const validItems = [];       // 可以审核的项 (状态不在 forbiddenStatuses 中)
            const invalidItems = [];     // 不可以审核的项

            selectdata.value.forEach(item => {
                if (forbiddenStatuses.includes(item.al_status)) {
                    invalidItems.push(item);
                } else {
                    validItems.push(item);
                }
            });

            // 如果没有任何可以审核的项，则直接提示并阻止
            if (validItems.length === 0) {
                let message = '选中的数据均为已处理状态（';
                const uniqueLabels = [...new Set(invalidItems.map(item => forbiddenStatusLabelMap[item.al_status] || `状态${item.al_status}`))];
                message += uniqueLabels.join('、');
                message += '），无法进行审核操作。';
                ElMessage.warning(message);
                return; // 阻止函数继续执行
            }

            if (invalidItems.length > 0) {
                let message = `选中的数据中包含 ${invalidItems.length} 条已处理状态（`;
                const uniqueLabels = [...new Set(invalidItems.map(item => forbiddenStatusLabelMap[item.al_status] || `状态${item.al_status}`))];
                message += uniqueLabels.join('、');
                message += '）的单据，将仅对其他单据执行审核。';
                ElMessage.info(message);
            }
            auditForm.selectedIds = validItems.map(item => item.al_id);
            auditForm.status = 3; // 默认驳回
            // 显示审核对话框
            showAuditDialog.value = true;
        }

        // 添加提交审核方法
        function submitAudit() {
        if (!auditForm.status) {
            ElMessage.warning('请选择审核状态');
            return;
        }

        // 创建请求数组
        const requests = auditForm.selectedIds.map(id => {
            const us = JSON.parse(sessionStorage.getItem("user"));
            return http.put(`/Allot_h/GetAudit?al_id=${id}&al_status=${auditForm.status}&user=${us?.name}`);
        });

        // 执行批量请求
        Promise.all(requests)
            .then(results => {
            // 处理结果统计
            const successCount = results.filter(res => res.data > 0).length;
            
            if (successCount === auditForm.selectedIds.length) {
                ElMessage.success(`成功审核 ${successCount} 条数据`);
            } else {
                ElMessage.warning(`成功审核 ${successCount} 条，失败 ${auditForm.selectedIds.length - successCount} 条`);
            }
            
            // 刷新数据并清空选择
            All();
            tableRef.value.clearSelection();
            showAuditDialog.value = false;
            auditForm.status = null;
            })
            .catch(err => {
            console.error(err);
            ElMessage.error('审核失败');
            });
        }

        // 撤销方法
        function quash(id) {
            ElMessageBox.confirm('确定要撤销该调拨单吗？', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                try {
                // 调用后端逻辑删除接口（PUT 方法）
                const us = JSON.parse(sessionStorage.getItem("user"));
                const res = await http.put(`/Allot_h/GetAudit?al_id=${id}&al_status=${2}&user=${us?.name}`);

                if (res.status === 200) {
                    ElMessage.success('删除成功');
                    All();
                }
                } catch (err) {
                    ElMessage.error('删除失败');
                    console.error(err);
                }
            }).catch(() => {
                // 用户取消操作
            });
        }
        //#endregion

        // 初始化加载
        onMounted(() => {
            All();
            alstatus();
            instockstatus();
            outstockstatus();
            GetWarehouses();
            GetUser();
            GetAllocationtype();
        });

        function jump(id = null) {
            if(id)
                router.push({ path: 'allotupdate', query: { id: id } });
            else
                router.push('allotadd');
        }


        function Jumptodetail(id,code) {
            router.push({ path: 'allocationdetail', query: { id: id ,code:code} });
        }

        return {
            Allocationtype,
            quash,
            Jumptodetail,
            jump,
            showAuditDialog,
            auditForm,
            GetEnable,
            submitAudit,
            exportData,
            instockoutstockOptions,
            alstatusdata,
            instockstatusdata,
            outstockstatusdata,
            selectdata,
            SelectChange,
            tableRef,
            deletiondata,
            DeleteAll,
            displayData,
            handleDateChange,
            dateRange,
            rules,
            rows,
            currentPage,
            handlePageChange,
            Reset,
            dictref,
            Search,
            dictform,
            dictdata,
            requesttransferdateRange,
            createdateRange,
            auditdateRange,
            supplierformsenior,
            warehousedata,
            userdata,
            requesttransferdateRange,
            requesttransferhandleDateChange,
            createdateRange,
            createhandleDateChange,
            auditdateRange,
            audithandleDateChange,
            GetSeniorFenYe,
            resetSeniorForm,
            drawer
        }
    }
}
</script>

<style scoped>
</style>
